package com.boarsoft.boar.agent.plugin;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.boar.agent.AgentConfig;
import com.boarsoft.common.Util;
import com.boarsoft.common.util.FileUtil;

public class TableHandlerImpl implements TableHandler {
	private Logger log = LoggerFactory.getLogger(TableHandlerImpl.class);
	/** 备份哪个库 */
	protected String dbId;
	protected String tableName;
	protected String countSql;
	protected String querySql;
	/** 备份路径 */
	protected String backupPath = "/home/db/backup";

	@Override
	public Object process(String entry, Object data, Throwable throwable)
			throws Throwable {
		if ("backup".equals(entry)) {
			this.backup(data);
		} else if ("restore".equals(entry)) {
			this.restore(data);
		}
		return null;
	}

	@Override
	public void restore(Object data) {
	}

	@Override
	public void backup(Object data) {
		String fp = new StringBuilder().append(backupPath).append(dbId).append("/")
				.append(tableName).append("/").append(Util.date2str("yyyyMMddHHmmss"))
				.append(".bak").toString();

		String driver = AgentConfig.getProperty(dbId.concat(".driver"));
		String url = AgentConfig.getProperty(dbId.concat(".url"));
		// String port = AgentConfig.getProperty(dbId.concat(".port"));
		String username = AgentConfig.getProperty(dbId.concat(".username"));
		String password = AgentConfig.getProperty(dbId.concat(".password"));

		Connection conn = null;
		Statement stmt = null;

		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);
			conn.setAutoCommit(false);
			stmt = conn.createStatement();

			ResultSet ctRs = stmt.executeQuery(countSql);
			ctRs.next();
			ctRs.getInt(0);

			File f = new File(fp);
			// TODO 分页逐页追加到文件
			ResultSet qryRs = stmt.executeQuery(querySql);
			while (qryRs.next()) {
				// TODO 遍历所有字段，生成csv格式的字符串
				String ln = "";
				FileUtil.write(f, ln, true, true, "UTF-8");
			}
		} catch (Exception e) {
			log.error("Error on backup table {} by SQL {}", tableName, querySql, e);
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					log.error("Can not close statment", e);
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					log.error("Can not close connection", e);
				}
			}
		}
	}
}
